import { useUserStore } from '@/store/user'
import errorCode from '@/utils/errorCode'
import config from '@/utils/config'
import {getToken} from '@/utils/auth'

let timeout = 10000
const baseUrl = config.baseUrl

const request = config => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	if (getToken() && !isToken) {
		config.header['Authorization'] = getToken()
	}
	return new Promise((resolve, reject) => {
		if (config.loading) uni.showLoading({title: '加载中'})
		uni.request({
			method: config.method || 'get',
			timeout: config.timeout || timeout,
			url: config.baseUrl || baseUrl + config.url,
			data: config.data,
			header: config.header,
			dataType: 'json',
			success: (response) => {
				if (config.loading) uni.hideLoading()
				let { statusCode, data} = response
				if (statusCode != 200) {
					uni.showToast({
						icon: 'none',
						title: '后端接口连接异常'
					})
					reject('后端接口连接异常')
					return
				}
				const code = data.code || 200
				const msg = errorCode[code] || data.msg || errorCode['default']
				if (code === 401) {
					let content = getToken()? '登录状态已过期，您可以继续留在该页面，或者重新登录?' : '未登录，您可以继续留在该页面，或者去登录'
					uni.showModal({
						title: '提示',
						content,
						cancelText: '取消',
						confirmText: '确定',
						success: function(res) {
							if (res.confirm) {
								if (getToken()) {
									const user = useUserStore()
									user.logOutAction().then(res => {
										uni.navigateTo({ url: '/pages/login' })
									})
								} else {
									uni.navigateTo({ url: '/pages/login' })
								}
							}
						}
					})
					reject('无效的会话，或者会话已过期，请重新登录。')
				} else if (code !== 200) {
					uni.showToast({
						icon: 'none',
						title: msg
					})
					reject(code)
				} else resolve(data)
			},
			fail: (error) => {
				if (config.loading) uni.hideLoading()
				let { errMsg } = error
				if (errMsg === 'Network Error') {
					errMsg = '后端接口连接异常'
				} else if (errMsg.includes('timeout')) {
					errMsg = '系统接口请求超时'
				} else if (errMsg.includes('Request failed with status code')) {
					errMsg = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				uni.showToast({
					icon: 'none',
					title: errMsg
				})
				reject(error)
			}
		})
	})
}

export default request